package com.example.nextgen.function.impl;

import com.example.nextgen.event.Event;
import com.example.nextgen.function.ExtendFunction;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Component
public class Program implements ExtendFunction {

    public void exeWithPrint(String command) throws Exception {
        Process process = Runtime.getRuntime().exec(command);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream())
        );
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        int exitCode = process.waitFor();
        if (exitCode != 0 && exitCode != 1) {
            throw new RuntimeException(command + " execution failed with exit code "+exitCode);
        }
    }

    public void exe(String command) throws IOException {
        Runtime.getRuntime().exec(command);
    }

    @Override
    public Event getRuntimeEvent() {
        return Event.FILE_WRITE_COMPLETE;
    }
}
